package com.changgou.goods.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.changgou.entity.Result;
import com.changgou.goods.dao.*;
import com.changgou.goods.pojo.CategoryBrand;
import com.changgou.goods.pojo.Goods;
import com.changgou.goods.pojo.Sku;
import com.changgou.goods.pojo.Spu;
import com.changgou.goods.service.GoodsService;
import com.changgou.util.IdWorker;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.commons.lang.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import sun.awt.geom.AreaOp;
import tk.mybatis.mapper.entity.Example;

import javax.jws.Oneway;
import java.util.*;

/**
 * @program: changgou_parent
 * @author: zhanzhewan
 * @create: 2020-03-23 21:06
 **/
@Service
public class GoodsServiceImpl implements GoodsService {

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Autowired
    CategoryBrandMapper categoryBrandMapper;

    @Autowired
    BrandMapper brandMapper;

    @Autowired
    IdWorker idWorker;

    @Autowired
    CategoryMapper categoryMapper;

    @Autowired
    SpuMapper spuMapper;

    @Autowired
    SkuMapper skuMapper;
    
    /**
     * @Description: 查询所有的商品以及库存 数据量太大 基本不使用 
     * @Param:  
     * @return: 
     */ 
    @Override
    public ArrayList<Goods> findAll() {
        ArrayList<Goods> goodlist = new ArrayList<>();
        List<Spu> spus = spuMapper.selectByExample(null); //没有查询条件就是查询所有
        if(spus != null){
            Goods goods = new Goods();
            for (Spu spu : spus) {
                Example example = new Example(Sku.class);
                Example.Criteria criteria = example.createCriteria();
                criteria.andEqualTo("spuId",spu.getId());
                List<Sku> skus = skuMapper.selectByExample(example);
                goods.setSpu(spu);
                goods.setSkuList(skus);
                goodlist.add(goods);
            }
        }

        PageHelper.startPage(1,100);
        return goodlist;

    }

    /**
     * @Description: 添加商品以及库存 
     * @Param:  
     * @return: 
     */ 
    @Override
    public void add(Goods goods) {
        if (goods != null) {
            long spuId = idWorker.nextId();
            Spu spu = goods.getSpu();
            spu.setId(String.valueOf(spuId));
            spu.setIsDelete(String.valueOf(0));
            spu.setIsMarketable("0");
            spu.setStatus("0");
            // insertSelective是自动判断传入对象的属性为不为空  如果为空 就不参与映射过程
            spuMapper.insertSelective(spu);

            CategoryBrand categoryBrand = new CategoryBrand();
            categoryBrand.setBrandId(spu.getBrandId());
            categoryBrand.setCategoryId(spu.getCategory3Id());

            int co = categoryBrandMapper.selectCount(categoryBrand);
            if (co == 0) {
                categoryBrandMapper.insertSelective(categoryBrand);
            }

            // 添加skuList
            insertSku(goods);
        }

    }

    @Override
    public void update(Goods goods) {
        // 修改spu  有这个selective的都会判断为不为空 如果为空则不更改
        spuMapper.updateByPrimaryKeySelective(goods.getSpu());
        // 修改sku 先删除 再添加  byExample根据外键 根据条件
        Spu spu = goods.getSpu();

        List<Sku> skuList = goods.getSkuList();
        // 先删除
        for (Sku sku : skuList) {
            Example example = new Example(Sku.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("spuId",goods.getSpu().getId());
            skuMapper.deleteByExample(example);
        }

        // 再添加skuList
        insertSku(goods);
    }

    @Override
    public Goods find(String id) {
        Spu spu = spuMapper.selectByPrimaryKey(id);
        // ByExample都是按照条件查询
        Example example = new Example(Sku.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("spuId",spu.getId());
        List<Sku> skus = skuMapper.selectByExample(example);
        Goods goods = new Goods();
        goods.setSpu(spu);
        goods.setSkuList(skus);
        return goods;
    }

    @Override
    public void Audit(String id) {
        Spu spu = spuMapper.selectByPrimaryKey(id);
        spu.setStatus("1");
        spuMapper.updateByPrimaryKeySelective(spu);

    }

    @Override
    public void shangjia(String id) {
        // 更改数据库的上架状态  ismarktable
        Spu spu = spuMapper.selectByPrimaryKey(id);
        if("0".equals(spu.getStatus())){
            throw new RuntimeException("还未审核通过，不能上架");
        }
        // 已审核通过 可以进行修改
        spu.setIsMarketable("1");
        spuMapper.updateByPrimaryKeySelective(spu);

        // 将spu ID发给rabbitmq
        rabbitTemplate.convertAndSend("goods_up_exchange","",id);
    }

    @Override
    public void xiajia(String id) {
        Spu spu = spuMapper.selectByPrimaryKey(id);
        spu.setIsMarketable("0");
        spuMapper.updateByPrimaryKeySelective(spu);
    }

    void insertSku(Goods goods){
        Spu spu = goods.getSpu();
        // 再添加
        List<Sku> skuList = goods.getSkuList();
        if (skuList.size() != 0){
            for (Sku sku : skuList) {
                sku.setSpuId(spu.getId());
                sku.setId(String.valueOf(idWorker.nextId()));
                sku.setCategoryId(spu.getCategory3Id());
                sku.setCategoryName(categoryMapper.selectByPrimaryKey(spu.getCategory3Id()).getName());
                if (StringUtils.isEmpty(sku.getSpec())){
                    sku.setSpec("{}");
                }
                sku.setCreateTime(new Date());
                sku.setUpdateTime(new Date());
                sku.setBrandName(brandMapper.selectByPrimaryKey(spu.getBrandId()).getName());

                // 库存名称 = 商品名称 + 规格  从前端传过来的spec值是一个json数据
                String title = sku.getName();
                try {
                    Map<String,String> spcMap = JSON.parseObject(sku.getSpec(), Map.class);
                    for (Object value : spcMap.values()) {
                        title+=value;
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }

                sku.setName(title.toString());
                skuMapper.insertSelective(sku);
                System.out.println("添加成功");
            }
        }
    }
}
